from django.conf.urls.defaults import *
from django.http import HttpResponsePermanentRedirect

from journal.models import Post
from bistrot.models import Thought

def redirect(url):
    def inner(request):
        return HttpResponsePermanentRedirect(url)
    return inner

def redirect_rss(url):
    def inner(request):
        tag = request.GET.get('cat', None)
        type = request.GET.get('co', None)
        if tag:
            return HttpResponsePermanentRedirect('%s%s/' % (url, tag.lower()))
        elif type:
            return HttpResponsePermanentRedirect('%s%s/' % (url, 'commentaires'))
        else:
            return HttpResponsePermanentRedirect('%s%s/' % (url, 'journal'))
    return inner

def redirect_tag(url):
    def inner(request, tag):
        return HttpResponsePermanentRedirect(url % {'tag': tag.lower()})
    return inner

def redirect_post():
    def inner(request, slug):
        post = Post.published.get(slug=slug)
        return HttpResponsePermanentRedirect(post.get_absolute_url())
    return inner

## Warning, order is important!
urlpatterns = patterns('',
    ('index.php/archives',                  redirect('/archives/')),
    ('index.php/(?P<tag>[A-Z][-\w]+)/$',    redirect_tag('/%(tag)s/')),
    ('index.php/(?P<slug>[-\w]+)/$',        redirect_post()),
    ('index.php/$',                         redirect('/journal/')),
    ('rss.php$',                            redirect_rss('/feeds/rss/')),
    ('atom.php$',                           redirect_rss('/feeds/rss/')),
    ('rss_ailleurs.xml$',                   redirect('/feeds/rss/bistrot/')),
)

